/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ResultFrame.java
 *
 * Created on 2010-04-08, 22:39:07
 */

package nsdh.view;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import nsdh.*;
import nsdh.model.script_models.*;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;


/**
 *
 * @author vtq
 */
public class ResultFrame extends javax.swing.JFrame {

    /** Creates new form ResultFrame */
    public ResultFrame(NsdhController nsdhController) {
        initComponents();
        this.nsdhController = nsdhController;
        initOtherComponents();
        refreshResults();
        this.setLocationRelativeTo(null);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        serverClientConnectionComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        avgThroughputTextField = new javax.swing.JTextField();
        avgJitterTextField = new javax.swing.JTextField();
        avgDelayTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        packetLossRateTextField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        chartDataComboBox = new javax.swing.JComboBox();
        chartPanel = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Wyniki symulacji");
        setBounds(new java.awt.Rectangle(100, 50, 0, 0));
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setResizable(false);

        serverClientConnectionComboBox.setAutoscrolls(true);
        serverClientConnectionComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serverClientConnectionComboBoxActionPerformed(evt);
            }
        });

        jLabel1.setText("Połączenie serwer-klient:");

        jLabel2.setText("Średnia przepustowość [kbps]: ");

        jLabel3.setText("Średni jitter [ms]:");

        jLabel5.setText("Packet Loss Rate:");

        avgThroughputTextField.setEditable(false);

        avgJitterTextField.setEditable(false);

        avgDelayTextField.setEditable(false);

        jLabel4.setText("Średnie opóźnienie [ms]:");

        packetLossRateTextField.setEditable(false);

        jLabel6.setText("Dane na wykresie:");

        chartDataComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Przepustowość/Czas", "Jitter/Czas", "Opoznienie/Czas" }));
        chartDataComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chartDataComboBoxActionPerformed(evt);
            }
        });

        chartPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        chartPanel.setPreferredSize(new java.awt.Dimension(800, 500));

        javax.swing.GroupLayout chartPanelLayout = new javax.swing.GroupLayout(chartPanel);
        chartPanel.setLayout(chartPanelLayout);
        chartPanelLayout.setHorizontalGroup(
            chartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 821, Short.MAX_VALUE)
        );
        chartPanelLayout.setVerticalGroup(
            chartPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 477, Short.MAX_VALUE)
        );

        chartPanel.setLayout(new BorderLayout());

        jButton1.setText("Zamknij");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(chartDataComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(avgJitterTextField)
                                    .addComponent(avgThroughputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(27, 27, 27)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5))
                                .addGap(29, 29, 29)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(avgDelayTextField)
                                    .addComponent(packetLossRateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(serverClientConnectionComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(chartPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 825, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(380, 380, 380)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(serverClientConnectionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(avgThroughputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(avgJitterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(chartDataComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(avgDelayTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(packetLossRateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(chartPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 481, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void serverClientConnectionComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serverClientConnectionComboBoxActionPerformed
        refreshResults();
    }//GEN-LAST:event_serverClientConnectionComboBoxActionPerformed

    private void chartDataComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chartDataComboBoxActionPerformed
        refreshResults();
    }//GEN-LAST:event_chartDataComboBoxActionPerformed



    private void refreshResults(){

        if (serverClientConnectionComboBox.getSelectedItem() != null){
            String selectedServerClientConnectionLabel = (String)serverClientConnectionComboBox.getSelectedItem();
            String selectedServerClientConnectionName = serverClientConnectionComboBoxMap.get(selectedServerClientConnectionLabel);
            
            String avgThroughput = "" + nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).avgThroughput;
            String avgDelay = "" + nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).avgDelay;
            String packetLossRate = "" + nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).packetLossRate;
            String avgJitter = "" + nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).avgJitter;
            
            this.avgThroughputTextField.setText(avgThroughput);
            this.avgDelayTextField.setText(avgDelay);
            this.packetLossRateTextField.setText(packetLossRate);
            this.avgJitterTextField.setText(avgJitter);

            //aktualizuje dane na wykresie, gdy wybrany checkbox 0-przepustowosc, 1-jitter
            if (chartDataComboBox.getSelectedIndex() == 0){
                //tworz wykres przepustowosci
                XYSeries series = new XYSeries("Przepustowosc");

                for(Double throughputStatTime: nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).chartStatsThroughput.keySet()){
                    series.add(throughputStatTime.doubleValue(), nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).chartStatsThroughput.get(throughputStatTime).doubleValue());
                }
                //dodaje linie na poczatku i koncu grafu y=0
                series.add(series.getMinX()-1, 0);
                series.add(0, 0);

                if(Double.parseDouble(nsdhController.nsdhModel.scenario.total_time)>series.getMaxX()){
                    series.add(series.getMaxX()+1, 0);
                    series.add(Double.parseDouble(nsdhController.nsdhModel.scenario.total_time), 0);
                }
                

                XYDataset xyDataset = new XYSeriesCollection(series);
                JFreeChart chart = ChartFactory.createXYLineChart
                                     (null,  // Title
                                      "Czas [s]",           // X-Axis label
                                      "Przepustowosc [kbps]",           // Y-Axis label
                                      xyDataset,          // Dataset
                                      PlotOrientation.VERTICAL,                // Show legend
                                      false,                // Show legend
                                      false,
                                      false
                                     );
                innerChartPanel.setChart(chart);

            }
            else if (chartDataComboBox.getSelectedIndex() == 1){

                //tworz wykres jitter
                XYSeries series = new XYSeries("Jitter");

                for(Double jitterStatTime: nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).chartStatsJitter.keySet()){
                    series.add(jitterStatTime.doubleValue(), nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).chartStatsJitter.get(jitterStatTime).doubleValue());
                }
                //dodaje linie na poczatku i koncu grafu y=0
                series.add(series.getMinX()-1, 0);
                series.add(0, 0);

                if(Double.parseDouble(nsdhController.nsdhModel.scenario.total_time)>series.getMaxX()){
                    series.add(series.getMaxX()+1, 0);
                    series.add(Double.parseDouble(nsdhController.nsdhModel.scenario.total_time), 0);
                }
                

                XYDataset xyDataset = new XYSeriesCollection(series);
                JFreeChart chart = ChartFactory.createXYLineChart
                                     (null,  // Title
                                      "Czas [s]",           // X-Axis label
                                      "Jitter [ms]",           // Y-Axis label
                                      xyDataset,          // Dataset
                                      PlotOrientation.VERTICAL,                // Show legend
                                      false,                // Show legend
                                      false,
                                      false
                                     );
                innerChartPanel.setChart(chart);
            }else if (chartDataComboBox.getSelectedIndex() == 2){

                //tworz wykres jitter
                XYSeries series = new XYSeries("Opoznienie");

                for(Double delayStatTime: nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).chartStatsDelay.keySet()){
                    series.add(delayStatTime.doubleValue(), nsdhController.nsdhModel.results.flowResultsList.get(nsdhController.nsdhModel.results.serverClientConnectionFlowIdDictionary.get(selectedServerClientConnectionName)).chartStatsDelay.get(delayStatTime).doubleValue());
                }
                //dodaje linie na poczatku i koncu grafu y=0
                series.add(series.getMinX()-1, 0);
                series.add(0, 0);

                if(Double.parseDouble(nsdhController.nsdhModel.scenario.total_time)>series.getMaxX()){
                    series.add(series.getMaxX()+1, 0);
                    series.add(Double.parseDouble(nsdhController.nsdhModel.scenario.total_time), 0);
                }


                XYDataset xyDataset = new XYSeriesCollection(series);
                JFreeChart chart = ChartFactory.createXYLineChart
                                     (null,  // Title
                                      "Czas [s]",           // X-Axis label
                                      "Opoznienie [ms]",           // Y-Axis label
                                      xyDataset,          // Dataset
                                      PlotOrientation.VERTICAL,                // Show legend
                                      false,                // Show legend
                                      false,
                                      false
                                     );
                innerChartPanel.setChart(chart);
            }
            
        }
        

        
    }

    /**
     * Inicjalizuje wykres,checkboxy i inne
     */
    private void initOtherComponents(){

        //inicjalizacja wykresu
        XYSeries series = new XYSeries("Przepustowosc");
        XYDataset xyDataset = new XYSeriesCollection(series);
        JFreeChart chart = ChartFactory.createXYLineChart
                             (null,  // Title
                              "Przepustowosc [kbps]",           // X-Axis label
                              "Czas [s]",           // Y-Axis label
                              xyDataset,          // Dataset
                              PlotOrientation.HORIZONTAL,                // Show legend
                              false,                // Show legend
                              false,
                              false
                             );
        innerChartPanel = new ChartPanel(chart, false, true, false, true, false);
        innerChartPanel.setMouseZoomable(true);
        chartPanel.add(innerChartPanel);
        pack();

        //tworzy mape nazwa wyswietlana w combobox -> server_client_connection name
        serverClientConnectionComboBoxMap = new HashMap<String,String>();
        for(Server_client_connection server_client_connection: nsdhController.nsdhModel.network_structure.server_client_connection_list.values()){
            String comboBoxLabel = server_client_connection.server_pc + " --> " + server_client_connection.client_pc + " [" + server_client_connection.service + "]";
            serverClientConnectionComboBoxMap.put(comboBoxLabel, server_client_connection.name);
        }

        //inicjalizuje combobox server-client-connection
        serverClientConnectionComboBox.setModel(new javax.swing.DefaultComboBoxModel(serverClientConnectionComboBoxMap.keySet().toArray()));

    }

    private void createServerClientConnectionComboBoxList(){
        this.avgDelayTextField.setText("234234");
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField avgDelayTextField;
    private javax.swing.JTextField avgJitterTextField;
    private javax.swing.JTextField avgThroughputTextField;
    private javax.swing.JComboBox chartDataComboBox;
    private javax.swing.JPanel chartPanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JTextField packetLossRateTextField;
    private javax.swing.JComboBox serverClientConnectionComboBox;
    // End of variables declaration//GEN-END:variables
    private ChartPanel innerChartPanel; //panel z wykresem
    private HashMap<String,String> serverClientConnectionComboBoxMap; //mapuje wybrany string w combo do name w server_client_connection
    protected NsdhController nsdhController;
}
